//
//  YRNetworkTools.swift
//  YR 微博
//
//  Created by cyr on 15/10/9.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit
import AFNetworking
private let YRErrorDomainName = "com.itheima.error.network"

 /// 枚举
private enum YRNetworkError: Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    // 错误描述
    private var errorDescrption: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token 为空"
        }
    }
    /// 根据枚举类型,返回对应的错误
        private func error() -> NSError {
            return NSError(domain: YRErrorDomainName, code: rawValue, userInfo: [YRErrorDomainName:errorDescrption])
        }
    }

 /// 网络访问方法
private enum YRNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}


class YRNetworkTools: AFHTTPSessionManager {
    
 /// MARK: - 应用程序信息
    private let clientId = 2926327607
    private let appsectrt = "aa6ceaf73deed7ed3bed2520690c42f1"
    let redirectUri = "http://www.baidu.com"
    
 /// MARK: - 类型定义
     typealias YRNetFinishedCallBack = (result: [String:AnyObject]?,error:NSError?) ->()

    // 创建单利
    static let sharedTools: YRNetworkTools = {
       
        let baseURL = NSURL(string: "https://api.weibo.com/")!
        let tools = YRNetworkTools(baseURL: baseURL)
        
        tools.responseSerializer.acceptableContentTypes = NSSet (objects:"application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>;
        
        return tools
    }()
    
    // 获取 TOKEN
    func loadAccessToken (code:String, finished: YRNetFinishedCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":clientId,
            "client_secret":appsectrt,
            "grant_type":"authorization_code",
            "code" : code,
            "redirect_uri" : redirectUri
        ]
        
        request(YRNetworkMethod.POST, urlString: urlString, param: params as! [String : AnyObject], finished: finished)
        
    }
    
    // MARK: - 封装 AFN 网络请求方法
    private func request(method:YRNetworkMethod, urlString:String, param: [String: AnyObject], finished: YRNetFinishedCallBack) {
        
        // 1.定义成功的闭包
        let seccessCallBack: (NSURLSessionDataTask, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String : AnyObject]{
                
                finished(result: result, error: nil)
                
            } else {
                print("没有数据")
                let error = NSError(domain: YRErrorDomainName, code: -1, userInfo: ["errorMessage" : "空数据"])
                finished(result: nil, error: error)
            }
            }
        
        
        // 2.定义失败的闭包
        let failedCallBack:(NSURLSessionDataTask!,NSError!) -> Void = { (_, error) -> Void in
            print(error)
            finished(result: nil, error: error)
        }

        
        // 3.根据 method 来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: param, success: seccessCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: param, success: seccessCallBack, failure: failedCallBack)
        }
        
    }
    
    // MARK: - 发布微博
    func sendStatus(status: String,finished: YRNetFinishedCallBack) {
        guard var params = tokenDict(finished) else {
            return
        }
        params["status"] = status
    
        request(YRNetworkMethod.POST, urlString: "2/statuses/update.json", param: params, finished: finished)
    }
    
    
    
    
    // MARK: - 加载微博数据
    
    /**
    since_id  若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    max_id    若指定此参数，则返回ID小于或等于max_id的微博，默认为0
    */
    func loadStatus(since_id: Int, max_id: Int, finished: YRNetFinishedCallBack) {
        // 判断 token 是否存在

        
        guard var params = tokenDict(finished) else {
            return
        }
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        let urlString = "2/statuses/home_timeline.json"
        
        request(YRNetworkMethod.GET, urlString: urlString, param: params, finished: finished)

    }
    
    /// 检查并生成 token 字典
    private func tokenDict(finished: YRNetFinishedCallBack) -> [String: AnyObject]? {
        // 判断 token 是否存在
        if YRUserAccount.sharedAccount?.access_token == nil {
            // 错误回调，token 为空
            let error = YRNetworkError.emptyTokenError.error()
            
            print(error)
            finished(result: nil, error: error)
            
            return nil
        }
        
        // 生成 token 字典返回
        return ["access_token": YRUserAccount.sharedAccount!.access_token!]
    }
   
    
    // MARK: - 加载用户数据
    func loadUserInfo(uid: String, finished: YRNetFinishedCallBack) {
        // 判断 token 是否存在
        guard var params = tokenDict(finished) else {
            return
        }
        
        let urlString = "2/users/show.json"
        params["uid"] = uid
        
        request(YRNetworkMethod.GET, urlString: urlString, param: params, finished: finished)
        }
    
    
    // MARK: - OAuth授权
    
    /*
    client_id 2926327607
    
    redirect_uri  aa6ceaf73deed7ed3bed2520690c42f1
    
    */
  
    
    // 返回 OAuth 授权地址
    func oauthUrl() -> NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: urlString)!
    }

}




